package com.beiming.kotlindemo.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.beiming.kotlindemo.Fruit
import com.beiming.kotlindemo.R

/**
 * Created by lingchen on 2020/5/7. 22:15
 * mail:lingchen52@foxmail.com
 */
class RecyclerViewFruitAdapter(private val fruitList: List<Fruit>) :
    RecyclerView.Adapter<RecyclerViewFruitAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val fruitImage: ImageView = view.findViewById(R.id.img_fruit)
        val fruitName: TextView = view.findViewById(R.id.tv_fruit)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.item_recyclerview, parent, false)
        val viewHolder = ViewHolder(view)
        viewHolder.itemView.setOnClickListener {
            val position = viewHolder.adapterPosition
            val fruit = fruitList[position]
            Toast.makeText(
                parent.context,
                "you clicked view ${fruit.fruit_name}",
                Toast.LENGTH_SHORT
            ).show()
        }
        viewHolder.fruitImage.setOnClickListener {
            val position = viewHolder.adapterPosition
            val fruit = fruitList[position]
            Toast.makeText(
                parent.context,
                "you clicked image ${fruit.fruit_name}",
                Toast.LENGTH_SHORT
            ).show()
        }
        return viewHolder
    }

    override fun getItemCount() = fruitList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fruit = fruitList[position]
        holder.fruitImage.setImageResource(fruit.fruit_img)
        holder.fruitName.text = fruit.fruit_name
    }
}